#!/usr/bin/env python
# -*- coding:utf-8 -*- #
from popcan.helper.viewhelper import require_login
from popcan.biz.accessors import CustomerAccessor
from popcan.db.daos import DesignerDao,CustomerDao
from popcan.cache.cachedaos import DesignerCacheDao,CustomerCacheDao
from popcan.model.models import Designer
from popcan.helper.requesthelper import JsonResult,respError,getParam as _p
from popcan.helper.validhelper import validRealname,validIdentnum,validContactnum,validAddress
import time

@require_login
def getCustomerInfo(request):
    session = request.affix['session']
    custId = session.custId
    customer = CustomerAccessor().getCustomer(custId)
    if not customer:
        return respError('customer_notexists','cannot find the customer info')
    customer.passwd = ''
    result = JsonResult()
    result.retdata['customer'] = customer
    return result.response()

@require_login
def upgrade(request):
    session = request.affix['session']
    custId = session.custId
    realname = _p(request,'realname','').strip()
    identnum = _p(request,'identnum','').strip()
    contactnum = _p(request,'contactnum','').strip()
    address = _p(request,'address','').strip()
    if not realname:
        return respError('realname_empty','you must fill realname')
    if not identnum:
        return respError('identnum_empty','you must fill identnum')
    if not contactnum:
        return respError('contact_empty','you must fill contactnum')
    if not address:
        return respError('address_empty','you must fill address')
    
    if not validRealname(realname):
        return respError('realname_illegal','not a valid realname')
    if not validContactnum(contactnum):
        return respError('contactnum_illegal','not a valid contactnum')
    if not validIdentnum(identnum):
        return respError('identnum_illegal','not a valid identnum')
    if not validAddress(address):
        return respError('address_illegal','not a valid address')
    
    customer = CustomerAccessor().getCustomer(custId)
    if not customer:
        return respError('customer_notexists','cannot find the customer info')
    if customer.upgraded:
        return respError('designer_already','you are already designer')
    
    createdate = time.time()
    designer = Designer(custId, realname, identnum, contactnum, address,createdate)
    DesignerDao().addDesigner(designer)
    DesignerCacheDao().save(designer)
    customer.upgraded = True
    CustomerDao().upgradeCustomer(customer)
    CustomerCacheDao().save(customer)
    result = JsonResult()
    return result.response()

